<?php

namespace App\Http\Controllers\AdminApi;

use App\Models\VmAdmin;
use App\Models\VueAdmin;
use App\Models\VueAdminMenu;
use App\Models\VueAdminRole;
use App\Models\VueAdminRoleUser;
use App\Services\VmService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class VmController extends BaseController
{
    public VmService $vmService;

    public function initialize(Request $request)
    {
        parent::initialize($request);
        $this->defaultOrder = [['filed' => 'id', 'order' => 'desc']];

        $this->modelName = 'Vm';
        $this->vmService = new VmService();
    }

    /**
     * 处理列表数据
     */
    protected function handleListData($data)
    {
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;

        $data = $model->formatDatas($data, ['source' => 'backend']);

        return $data;
    }

    /**
     * 筛选条件
     */
    protected function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['instance_id']) && $param['instance_id']) {
            $where[] = ['instance_id', 'like', '%' . trim($param['instance_id']) . '%'];
        }
        // if (isset($param['nickname']) && $param['nickname']) {
        //     $where[] = ['nickname', 'like', '%' . trim($param['nickname']) . '%'];
        // }

        return $where;
    }

    protected function evalData($request)
    {
        $param = $request->all();

        $data = [
            'id' => $param['id'],
            'instance_id' => $param['instance_id'],
            'region_id' => $param['region_id'],
            'type' => $param['type']
        ];
        return $data;
    }

    /**
     * Note - ECS实例列表
     * DateTime 2025/2/10 16:10
     * User Admin
     * @param $uinfo
     */
    public function list(Request $request)
    {
        $param = $request->all();

        $page = 1;
        $limit = 20;
        if (!empty($param['page'])) {
            $page = (int)$param['page'];
        }
        if (!empty($param['limit'])) {
            $limit = (int)$param['limit'];
        }
        $page = ($page - 1) * $limit;
        $sort_field = $param['sort_field'] ?? '';
        $sort_value = $param['sort_value'] ?? '';

        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;
        $field = $this->defaultField;
        $orders = $this->defaultOrder;
        $where = $this->getFilterWhere($request);
        if ($this->defaultWhere) {
            $where = array_merge($this->defaultWhere, $where);
        }
        if ($sort_field && $sort_value) {
            $order[] = [
                'filed' => $sort_field,
                'order' => $sort_field
            ];
        }

        $query = $model->query();
        foreach ($where as $value) {
            $query->where($value[0], $value[1], $value[2]);
        }
        foreach ($orders as $order) {
            $query->orderBy($order['filed'], $order['order']);
        }
        $admin_id = $this->admin->id;
        if ($admin_id !== 1){
            $roleId = VueAdminRoleUser::query()->where('admin_id', $admin_id)->value('role_id');
            $permission = VueAdminRole::query()->where('id', $roleId)->first()->toArray();
            $menu = VueAdminMenu::query()->whereIn('id', explode(',',$permission['access']))->get();
            $flag = false;
            foreach ($menu as $item){
                if ($item['route'] == 'vm/edit'){
                    $flag = true;
                    break;
                }
            }
            if (!$flag){
                // 开发角色：查询自己的账号下的VM
                $vmIdArr = VmAdmin::query()->where('admin_id', $admin_id)->pluck('vm_id');
                $query->whereIn('id', $vmIdArr);
            }else{
                if (isset($param['nickname']) && $param['nickname']) {
                    // 运营角色：查询所有的VM
                    $idArr = VueAdmin::query()->where('nickname', 'like', "%".$param['nickname']."%")->pluck('id');
                    $vmIdArr = VmAdmin::query()->whereIn('admin_id', $idArr)->pluck('vm_id');
                    $query->whereIn('id', $vmIdArr);
                }
            }
        }else {
            if (isset($param['nickname']) && $param['nickname']) {
                // 超级管理员：查询所有的VM
                $idArr = VueAdmin::query()->where('nickname', 'like', "%".$param['nickname']."%")->pluck('id');
                $vmIdArr = VmAdmin::query()->whereIn('admin_id', $idArr)->pluck('vm_id');
                $query->whereIn('id', $vmIdArr);
            }

        }
        $count = $query->count();
        $list = $query->take($limit)->skip($page)->get()->toArray();
        if ($list) {
            // 处理列表数据
            $list = $this->handleListData($list);
        }
        foreach ($list as &$instance) {
            $this->vmService->type = $instance['type'];
            $info = $this->vmService->info($instance['region_id'], $instance['instance_id']);
            logInfo('vm_info', $info);
            $instance['instance_id'] = $info['InstanceId'] ?? $instance['instance_id'];
            $instance['status'] = $info['Status'] ?? '-';
            $instance['name'] = $info['InstanceName'] ?? '-';
            $instance['ip'] = $info['Ip'] ?? '0.0.0.0';
        }

        $data = [
            'data' => $list,
            'total' => $count
        ];

        return api_response(self::STATUS_SUCCESS, '', $data);

    }

    public function save(Request $request)
    {
        DB::beginTransaction();
        try {
            $className = '\\App\\Models\\' . $this->modelName;
            $model = new $className;

            $data = $this->evalData($request);
            if (isset($data['id']) && $data['id']) {
                $info = $model->where('id', $data['id'])->select(['*'])->first();
                if (!$info) {
                    return api_response(self::STATUS_ERROR, '不存在', '');
                }
                $data['updated_at'] = time();
                $message = '保存失败';
                $result = $model->where('id', $data['id'])->update($data);

                // $afterAction = '_after_update';
            } else {
                $data['created_at'] = time();
                $message = '创建失败';
                $result = $model->create($data);
                $data['id'] = $result->id ?? 0;

                // $afterAction = '_after_insert';
            }
            if ($result === false) {
                return api_response(self::STATUS_ERROR, $message, []);
            }

            if ($request->input('user_id')){
                $user = $request->input('user_id');
                VmAdmin::query()->where('vm_id', $data['id'])->delete();
                foreach ($user as $item){
                    VmAdmin::query()->insert([
                        'vm_id' => $data['id'],
                        'admin_id' => $item
                    ]);
                }
            }


            if (isset($info)) {
                $afterRes = $this->afterUpdate($data, $info);
            } else {
                $afterRes = $this->afterInsert($data);
            }
            if ($afterRes['code'] != 1) {
                return api_response(self::STATUS_ERROR, $afterRes['msg'] ?? 'after error', []);
            }

            DB::commit();
            return api_response(self::STATUS_SUCCESS, self::MSG_SUCCESS, $data);
        } catch (Exception $e) {
            DB::rollBack();
            return api_response(self::STATUS_ERROR, '失败', $e->getMessage());
        }
    }


    /**
     * Note - 启动ECS实例
     * DateTime 2025/2/6 9:46
     * User Admin
     */
    public function start(Request $request)
    {
        $regionId = $request->input('region_id');
        $instanceId = $request->input('instance_id');
        $type = $request->input('type');
        // return api_response(self::STATUS_SUCCESS,'启动ECS实例',compact('regionId','instanceId'));
        $this->vmService->type = $type;
        $result = $this->vmService->start($regionId, $instanceId);
        if (!$result){
            return api_response(self::STATUS_ERROR, '启动失败');
        }
        return api_response(self::STATUS_SUCCESS,'启动成功');
    }

    /**
     * Note - 重启ECS实例
     * DateTime 2025/2/6 9:46
     * User Admin
     */
    public function restart(Request $request)
    {
        $regionId = $request->input('region_id');
        $instanceId = $request->input('instance_id');
        $type = $request->input('type');
        // return api_response(self::STATUS_SUCCESS,'重启ECS实例',compact('regionId','instanceId'));
        $this->vmService->type = $type;
        $result = $this->vmService->restart($regionId, $instanceId);
        if (!$result){
            return api_response(self::STATUS_ERROR, '重启失败');
        }
        return api_response(self::STATUS_SUCCESS,'重启成功');
    }

    /**
     * Note - ECS实例 停机不计费
     * DateTime 2025/2/6 9:47
     * User Admin
     */
    public function shoutDown(Request $request)
    {
        $regionId = $request->input('region_id');
        $instanceId = $request->input('instance_id');
        $type = $request->input('type');
        // return api_response(self::STATUS_SUCCESS,'停机不计费ECS实例',compact('regionId','instanceId'));
        $this->vmService->type = $type;
        $result = $this->vmService->shoutDown($regionId, $instanceId);
        if (!$result){
            return api_response(self::STATUS_ERROR, '停机失败');
        }
        return api_response(self::STATUS_SUCCESS,'停机成功');
    }

    public function regionList(Request $request)
    {
        $type = $request->input('type');
        $this->vmService->type = $type;
        $result = $this->vmService->regionList();
        if (!$result){
            return api_response(self::STATUS_ERROR, '');
        }
        return api_response(self::STATUS_SUCCESS,'',$result);

    }

    public function getStatus(Request $request)
    {
        $id = $request->input('id');
        $className = '\\App\\Models\\' . $this->modelName;
        $model = new $className;
        $query = $model->query();
        $list = $query->whereIn('id', $id)->get()->toArray();
        if ($list) {
            // 处理列表数据
            $list = $this->handleListData($list);
        }
        foreach ($list as &$instance) {
            $this->vmService->type = $instance['type'];
            $info = $this->vmService->info($instance['region_id'], $instance['instance_id']);
            logInfo('vm_info', $info);
            $instance['instance_id'] = $info['InstanceId'] ?? $instance['instance_id'];
            $instance['status'] = $info['Status'] ?? '-';
            $instance['name'] = $info['InstanceName'] ?? '-';
            $instance['ip'] = $info['Ip'] ?? '0.0.0.0';
        }
        $data = [
            'data' => $list,
        ];

        return api_response(self::STATUS_SUCCESS, '', $data);
    }

}
